import {
	Iap,
	IapTransactionState
} from "./iap.js"
export default class {
	constructor() {
		this.loadingIosPay = false;
		this.IosPayDisabled = true;
		this.IosPayProductId = "";
		this.IosPayProducts = [];
		this.IosPayProductList = [];
		this.IosPayIsError = false;
		this.IosPayGoodsId = 0;
		this.IosPayUserId = 0;
		this._iap = null;
	}

	async iosPayInit() {
		if (this._iap && this._iap._ready && !this.IosPayIsError) {
			this.restore();
			return false;
		}
		uni.showLoading({
			mask: true,
			title: '检测支付环境...'
		});
		this.IosPayIsError = false;
		// 创建实例
		this._iap = new Iap({
			products: this.IosPayProducts // 苹果开发者中心创建
		})
		try {
			// 初始化，获取iap支付通道
			await this._iap.init();
			// 从苹果服务器获取产品列表
			this.IosPayProductList = await this._iap.getProduct();
			this.IosPayProductList[0].checked = true;
			this.IosPayProductId = this.IosPayProductList[0].productid;
			// 填充产品列表，启用界面
			this.IosPayDisabled = false;
		} catch (e) {
			this.IosPayIsError = true;
			uni.showModal({
				title: "提示",
				content: e.message,
				showCancel: false
			});
		} finally {
			if (this._iap._ready && !this.IosPayIsError) {
				this.restore();
			} else {
				uni.hideLoading();
			}
		}
	}
	async restore() {
		// 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常
		// 在此处检查用户是否登陆
		// uni.showLoading({
		// 	mask: true,
		// 	title: '苹果验证中，请稍等'
		// });
		try {
			// 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
			const transactions = await this._iap.restoreCompletedTransactions({
				username: ''
			});
			if (!transactions.length) {
				return;
			}
			// 开发者业务逻辑，从服务器获取当前用户未完成的订单列表，和本地的比较
			// 此处省略
			for (let i = 0; i < transactions.length; i++) {
				const transaction = transactions[i];
				switch (transaction.transactionState) {
					case IapTransactionState.purchased:
						this.IosPayIsError = true;
						// 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
						uni.showLoading({
							mask: true,
							title: '您有一笔订单正在处理中...'
						})
						const order_sn = transaction.payment.username || uni.getStorageSync('IOSPAYORDERID');
						if (!order_sn) {
							this.IosPayIsError = false;
							return await this._iap.finishTransaction(transaction);
						}
						let result = await this.validatePaymentResult(order_sn, transaction, 0);
						// 验证通过，交易结束，关闭订单
						if (result) {
							await this._iap.finishTransaction(transaction);
						}
						break;
					case IapTransactionState.failed:
						this.IosPayIsError = false;
						// 关闭未支付的订单
						await this._iap.finishTransaction(transaction);
						break;
					default:
						break;
				}
			}
		} catch (e) {
			// 为了兼容高版本机型在取消订单时候出现的错误，重启后不存在
			if (e.errCode == -100 || e.message.indexOf("本地没有响应要移除的事务") > -1) {
				this.IosPayIsError = false;
				return;
			}
			this.IosPayIsError = true;
			uni.showModal({
				title: `restore${e.errCode}`,
				content: e.message,
				showCancel: false
			});
		} finally {
			if (this.IosPayIsError) {
				uni.hideLoading();
			} else {
				this.paymentIOS();
			}
		}
	}
	async paymentIOS() {
		if (this.loadingIosPay == true) {
			return;
		}
		this.loadingIosPay = true;
		uni.showLoading({
			mask: true,
			title: '正在支付中...'
		});
		let transaction;
		try {
			// 从开发者服务器创建订单
			// const order = await createOrderApi(this.IosPayGoodsId, 0, 2, this.IosPayUserId);
			const order = 'ssss';
			// orderId存在本地，防止丢失
			uni.setStorageSync('IOSPAYORDERID', order.orderId);
			// 请求苹果支付
			transaction = await this._iap.requestPayment({
				productid: order.bindId,
				manualFinishTransaction: true,
				quantity: 1,
				optimize: true,
				username: order.orderId, //根据业务需求透传参数，关联用户和订单关系
			});
			// 在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
			await this.validatePaymentResult(order.orderId, transaction);
			// 验证成功后关闭订单
			await this._iap.finishTransaction(transaction);
			// 支付成功
			this.paySuccess();
		} catch (e) {
			this._iap.finishTransaction(transaction);
			if (e.errCode == 2) {
				this.payError('取消支付')
			} else {
				this.payError()
			}
		} finally {
			this.loadingIosPay = false;
			uni.hideLoading();
		}
	}
	paySuccess() {
		uni.showToast({
			duration: 1500,
			title: '支付成功',
			icon: 'success'
		})
	}
	payError(title = '支付失败') {
		uni.showToast({
			duration: 1500,
			title,
			icon: 'error'
		})
	}
	/**
	 * 充值，then返回均代表 处理成功
	 * @param {Object} data 订单数据
	 */
	validatePaymentResult(orderId, data, type = 1) {
		return new Promise((resolve, reject) => {
			const fn = (loading = 1) => {
				fn(0);
				// payBack(orderId, data).then(res => {
				// 	// 处理成功
				// 	let obj = {
				// 		orderId: orderId,
				// 		orderString: JSON.stringify(data),
				// 	};
				// 	postOrderData(obj);
				// 	uni.hideLoading();
				// 	if (type == 0) {
				// 		this.successTip();
				// 	}
				// 	resolve(true);
				// }).catch(e => {
					// if (e.code == 201) { //处理成功-订单已更新
					// 	this.successTip();
					// 	uni.hideLoading();
					// 	resolve(true);
					// } else {
					// setTimeout(() => {
					// fn(0);
					// }, 1000)
					// }
				// })
			}
			fn(type == 0 ? 0 : 1);
		});
	}
	appleGoodsIdChange(id) {
		this.IosPayGoodsId = id;
	}
	appleUserIdChange(id) {
		this.IosPayUserId = id;
	}
	successTip() {
		// uni.showModal({
		// 	title: '温馨提示',
		// 	content: '您的待处理订单已经处理成功，充值金额已到您的账户余额中，请注查收！',
		// 	showCancel: false,
		// 	confirmText: '我知道了'
		// });
	}
}